package com.frame.hander;

import net.sf.json.JSONObject;

import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

/**
 * @author LRC
 * @createDate 2015年5月19日
 * @description 页面分页参数处理类
 */
public class PagerHander {
	
	public static class Pager{
		public boolean hasPre = true;
		public boolean hasNext = true;
		public int rowStart = 0;
		public int start = 1;
		public int end = 10;
		public long count;
		public int totalPage;
		public int pageSize;
		public int pageIndex;
		public boolean isHasPre() {
			return hasPre;
		}
		public void setHasPre(boolean hasPre) {
			this.hasPre = hasPre;
		}
		public boolean isHasNext() {
			return hasNext;
		}
		public void setHasNext(boolean hasNext) {
			this.hasNext = hasNext;
		}
		public int getStart() {
			return start;
		}
		public void setStart(int start) {
			this.start = start;
		}
		public int getEnd() {
			return end;
		}
		public void setEnd(int end) {
			this.end = end;
		}
		public long getCount() {
			return count;
		}
		public void setCount(long count) {
			this.count = count;
		}
		public int getTotalPage() {
			return totalPage;
		}
		public void setTotalPage(int totalPage) {
			this.totalPage = totalPage;
		}
		public int getPageSize() {
			return pageSize;
		}
		public void setPageSize(int pageSize) {
			this.pageSize = pageSize;
		}
		public int getPageIndex() {
			return pageIndex;
		}
		public void setPageIndex(int pageIndex) {
			this.pageIndex = pageIndex;
		}
		public int getRowStart() {
			return rowStart;
		}
		public void setRowStart(int rowStart) {
			this.rowStart = rowStart;
		}
	}
	
	public static Pager getPager(Page<Record> page,int showPagerNum){
		Pager p = new Pager();
		p.pageIndex = page.getPageNumber();
		p.pageSize = page.getPageSize();
		p.totalPage = page.getTotalPage();
		p.count = page.getTotalRow();
		p.rowStart = (p.pageIndex-1)*p.pageSize;
		if(p.pageIndex<=1){
			p.hasPre = false;
		}
		if(p.pageIndex>=p.totalPage){
			p.hasNext = false;
		}
		if(showPagerNum<=0){
			showPagerNum = 5;
		}
		//计算起始页
		if(p.totalPage<=showPagerNum){
			//如果总页数小于要显示的页码数，则显示全部
			p.start = 1;
			p.end = p.totalPage;
		}else{
			//计算如果从pageIndex起，最后要显示的页面
			int l = showPagerNum + p.pageIndex-1;
			if(l<=p.totalPage){
				p.start = p.pageIndex;
				p.end = l;
			}else{
				p.start = p.totalPage-showPagerNum+1;
				p.end = p.totalPage;
			}
		}
		return p;
	}
	
	public static JSONObject getJSONPager(Page<Record> page,int showPagerNum){
		Pager p = getPager(page, showPagerNum);
		return JSONObject.fromObject(p);
	}
}
